package cn.sh.tools.util;

import cn.hutool.system.OsInfo;
import cn.hutool.system.SystemUtil;
import lombok.extern.slf4j.Slf4j;

import javax.swing.*;
import java.lang.reflect.Method;

/**
 * @Description 浏览器工具
 * @Classname BrowserUtils
 * @Date 2023/7/25
 * @Author sh
 **/
@Slf4j
public class BrowserUtils {

    private static final String errMsg_en = "Error attempting to launch web browser";
    private static final String errMsg_zh_CN = "尝试启动web浏览器时出错";

    public static final String FILE_PREFIX = "file://";

    /**
     * 在 web浏览器 中打开指定的网页
     *
     * @param browserPath 浏览器程序全路径
     * @param url         An absolute URL of a web page (ex: "http://www.baidu.com/")
     */
    public static void openURL(String browserPath, String url) {
        try {
            if (log.isInfoEnabled()) {
                log.info("Opening URL: " + url);
            }

            OsInfo osInfo = SystemUtil.getOsInfo();

            if (osInfo.isWindows()) {
                // 方法一：使用默认浏览器打开特定网页。
                //Runtime.getRuntime()
                //        .exec("rundll32 url.dll,FileProtocolHandler " + url);

                // 方法二：使用指定浏览器打开特定网页。
                new ProcessBuilder(browserPath, url).start();
            } else if (osInfo.isMac()) {
                Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL",
                        String.class);
                openURL.invoke(null, url);
            } else if (osInfo.isLinux()) {
                String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null;
                     count++) {
                    if (Runtime.getRuntime().exec(
                            new String[]{"which", browsers[count]}).waitFor() ==
                            0) {
                        browser = browsers[count];
                    }
                }
                if (browser == null) {
                    throw new Exception("Could not find web browser");
                } else {
                    Runtime.getRuntime().exec(new String[]{browser, url});
                }
            } else {
                JOptionPane.showMessageDialog(null, errMsg_zh_CN);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, errMsg_zh_CN + ":\n" +
                    e.getLocalizedMessage());
        }
    }

    public static void openFile(String filePath) {
        openURL(null, FILE_PREFIX + filePath);
    }

}
